/**
 * 图表管理器 - 负责数据可视化和图表渲染
 * 使用Chart.js库进行图表绘制
 */

class ChartManager {
    constructor() {
        this.charts = new Map();
        this.defaultColors = {
            primary: '#2196f3',
            success: '#4caf50',
            warning: '#ff9800',
            danger: '#f44336',
            info: '#00bcd4',
            purple: '#9c27b0',
            indigo: '#3f51b5',
            teal: '#009688'
        };
        
        this.colorPalette = [
            '#2196f3', '#4caf50', '#ff9800', '#f44336',
            '#9c27b0', '#00bcd4', '#3f51b5', '#009688',
            '#795548', '#607d8b', '#e91e63', '#cddc39'
        ];
        
        // 设置Chart.js默认配置
        this.setupChartDefaults();
    }
    
    /**
     * 设置Chart.js默认配置
     */
    setupChartDefaults() {
        Chart.defaults.font.family = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
        Chart.defaults.font.size = 12;
        Chart.defaults.color = '#666';
        Chart.defaults.plugins.legend.display = true;
        Chart.defaults.plugins.legend.position = 'top';
        Chart.defaults.responsive = true;
        Chart.defaults.maintainAspectRatio = false;
    }
    
    /**
     * 销毁指定图表
     */
    destroyChart(chartId) {
        const chart = this.charts.get(chartId);
        if (chart) {
            chart.destroy();
            this.charts.delete(chartId);
        }
    }
    
    /**
     * 销毁所有图表
     */
    destroyAllCharts() {
        this.charts.forEach(chart => chart.destroy());
        this.charts.clear();
    }
    
    /**
     * 获取颜色
     */
    getColor(index) {
        return this.colorPalette[index % this.colorPalette.length];
    }
    
    /**
     * 生成渐变色
     */
    createGradient(ctx, color1, color2) {
        const gradient = ctx.createLinearGradient(0, 0, 0, 400);
        gradient.addColorStop(0, color1);
        gradient.addColorStop(1, color2);
        return gradient;
    }
    
    /**
     * 创建KPI卡片图表
     */
    createKPIChart(containerId, data) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        const canvas = container.querySelector('canvas');
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const chart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [data.current, data.target - data.current],
                    backgroundColor: [
                        this.defaultColors.primary,
                        'rgba(0,0,0,0.1)'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                cutout: '70%',
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        enabled: false
                    }
                },
                animation: {
                    animateRotate: true,
                    duration: 1000
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建库存状态图表
     */
    createInventoryChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const gradient = this.createGradient(ctx, 
            'rgba(33, 150, 243, 0.8)', 
            'rgba(33, 150, 243, 0.1)'
        );
        
        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.labels || [],
                datasets: [{
                    label: '库存数量',
                    data: data.inventory || [],
                    borderColor: this.defaultColors.primary,
                    backgroundColor: gradient,
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: this.defaultColors.primary,
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }, {
                    label: '安全库存',
                    data: data.safetyStock || [],
                    borderColor: this.defaultColors.warning,
                    backgroundColor: 'transparent',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    fill: false,
                    pointRadius: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        },
                        ticks: {
                            callback: function(value) {
                                return value.toLocaleString();
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end'
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8,
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ' + context.parsed.y.toLocaleString();
                            }
                        }
                    }
                },
                interaction: {
                    mode: 'nearest',
                    axis: 'x',
                    intersect: false
                },
                animation: {
                    duration: 1000,
                    easing: 'easeInOutQuart'
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建订单趋势图表
     */
    createOrderTrendChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.labels || [],
                datasets: [{
                    label: '新订单',
                    data: data.newOrders || [],
                    backgroundColor: this.defaultColors.success,
                    borderColor: this.defaultColors.success,
                    borderWidth: 1,
                    borderRadius: 4,
                    borderSkipped: false
                }, {
                    label: '已完成',
                    data: data.completedOrders || [],
                    backgroundColor: this.defaultColors.primary,
                    borderColor: this.defaultColors.primary,
                    borderWidth: 1,
                    borderRadius: 4,
                    borderSkipped: false
                }, {
                    label: '已取消',
                    data: data.cancelledOrders || [],
                    backgroundColor: this.defaultColors.danger,
                    borderColor: this.defaultColors.danger,
                    borderWidth: 1,
                    borderRadius: 4,
                    borderSkipped: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        stacked: false,
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        },
                        ticks: {
                            callback: function(value) {
                                return value.toLocaleString();
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end'
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8
                    }
                },
                animation: {
                    duration: 1000,
                    easing: 'easeInOutQuart'
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建采购执行情况图表
     */
    createProcurementChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.labels || ['采购计划', '采购执行', '采购完成', '采购延期'],
                datasets: [{
                    label: '采购订单数量',
                    data: data.values || [120, 95, 85, 10],
                    backgroundColor: [
                        this.defaultColors.primary,
                        this.defaultColors.success,
                        this.defaultColors.warning,
                        this.defaultColors.danger
                    ],
                    borderColor: [
                        this.defaultColors.primary,
                        this.defaultColors.success,
                        this.defaultColors.warning,
                        this.defaultColors.danger
                    ],
                    borderWidth: 1,
                    borderRadius: 4,
                    borderSkipped: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                animation: {
                    duration: 1000,
                    easing: 'easeInOutQuart'
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建生产效率监控图表
     */
    createProductionChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const gradient = this.createGradient(ctx, 
            'rgba(76, 175, 80, 0.8)', 
            'rgba(76, 175, 80, 0.1)'
        );
        
        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.labels || ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                datasets: [{
                    label: '生产效率(%)',
                    data: data.values || [85, 88, 92, 87, 90, 85, 89],
                    borderColor: this.defaultColors.success,
                    backgroundColor: gradient,
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: this.defaultColors.success,
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        },
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                animation: {
                    duration: 1000,
                    easing: 'easeInOutQuart'
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建配送绩效分析图表
     */
    createDeliveryChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const chart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: data.labels || ['准时配送', '延期配送', '提前配送'],
                datasets: [{
                    data: data.values || [75, 15, 10],
                    backgroundColor: [
                        this.defaultColors.success,
                        this.defaultColors.danger,
                        this.defaultColors.warning
                    ],
                    borderWidth: 2,
                    borderColor: '#fff',
                    hoverBorderWidth: 3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '60%',
                plugins: {
                    legend: {
                        position: 'bottom',
                        align: 'center'
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8,
                        callbacks: {
                            label: function(context) {
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = ((context.parsed / total) * 100).toFixed(1);
                                return context.label + ': ' + context.parsed + ' (' + percentage + '%)';
                            }
                        }
                    }
                },
                animation: {
                    animateRotate: true,
                    duration: 1000
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建质量指标统计图表
     */
    createQualityChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const chart = new Chart(ctx, {
            type: 'radar',
            data: {
                labels: data.labels || ['产品质量', '服务质量', '交付质量', '流程质量', '供应商质量'],
                datasets: [{
                    label: '质量评分',
                    data: data.values || [85, 90, 88, 92, 87],
                    borderColor: this.defaultColors.purple,
                    backgroundColor: this.defaultColors.purple + '20',
                    borderWidth: 2,
                    pointBackgroundColor: this.defaultColors.purple,
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8
                    }
                },
                scales: {
                    r: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            stepSize: 20
                        },
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        },
                        angleLines: {
                            color: 'rgba(0,0,0,0.1)'
                        },
                        pointLabels: {
                            font: {
                                size: 12
                            }
                        }
                    }
                },
                animation: {
                    duration: 1000
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建饼图
     */
    createPieChart(containerId, data, options = {}) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const colors = data.datasets?.[0]?.backgroundColor || 
                      data.labels?.map((_, index) => this.getColor(index)) || [];
        
        const chart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: data.labels || [],
                datasets: [{
                    data: data.data || [],
                    backgroundColor: colors,
                    borderColor: '#fff',
                    borderWidth: 2,
                    hoverBorderWidth: 3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: options.cutout || '50%',
                plugins: {
                    legend: {
                        position: options.legendPosition || 'right',
                        align: 'start'
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8,
                        callbacks: {
                            label: function(context) {
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = ((context.parsed / total) * 100).toFixed(1);
                                return context.label + ': ' + context.parsed.toLocaleString() + ' (' + percentage + '%)';
                            }
                        }
                    }
                },
                animation: {
                    animateRotate: true,
                    duration: 1000
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建雷达图
     */
    createRadarChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const chart = new Chart(ctx, {
            type: 'radar',
            data: {
                labels: data.labels || [],
                datasets: data.datasets?.map((dataset, index) => ({
                    label: dataset.label,
                    data: dataset.data,
                    borderColor: this.getColor(index),
                    backgroundColor: this.getColor(index) + '20',
                    borderWidth: 2,
                    pointBackgroundColor: this.getColor(index),
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4
                })) || []
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    r: {
                        beginAtZero: true,
                        max: 100,
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        },
                        angleLines: {
                            color: 'rgba(0,0,0,0.1)'
                        },
                        pointLabels: {
                            font: {
                                size: 12
                            }
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top'
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8
                    }
                },
                animation: {
                    duration: 1000
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 创建散点图
     */
    createScatterChart(containerId, data) {
        const canvas = document.getElementById(containerId);
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        this.destroyChart(containerId);
        
        const chart = new Chart(ctx, {
            type: 'scatter',
            data: {
                datasets: data.datasets?.map((dataset, index) => ({
                    label: dataset.label,
                    data: dataset.data,
                    backgroundColor: this.getColor(index),
                    borderColor: this.getColor(index),
                    borderWidth: 1,
                    pointRadius: 6,
                    pointHoverRadius: 8
                })) || []
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        type: 'linear',
                        position: 'bottom',
                        title: {
                            display: true,
                            text: data.xAxisLabel || 'X轴'
                        },
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        }
                    },
                    y: {
                        title: {
                            display: true,
                            text: data.yAxisLabel || 'Y轴'
                        },
                        grid: {
                            color: 'rgba(0,0,0,0.1)'
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top'
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'rgba(255,255,255,0.2)',
                        borderWidth: 1,
                        cornerRadius: 8,
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': (' + 
                                       context.parsed.x + ', ' + context.parsed.y + ')';
                            }
                        }
                    }
                },
                animation: {
                    duration: 1000
                }
            }
        });
        
        this.charts.set(containerId, chart);
        return chart;
    }
    
    /**
     * 更新图表数据
     */
    updateChart(chartId, newData) {
        const chart = this.charts.get(chartId);
        if (!chart) return;
        
        // 更新数据
        if (newData.labels) {
            chart.data.labels = newData.labels;
        }
        
        if (newData.datasets) {
            chart.data.datasets = newData.datasets;
        } else if (newData.data) {
            chart.data.datasets[0].data = newData.data;
        }
        
        // 重新渲染
        chart.update('active');
    }
    
    /**
     * 调整图表大小
     */
    resizeChart(chartId) {
        const chart = this.charts.get(chartId);
        if (chart) {
            chart.resize();
        }
    }
    
    /**
     * 调整所有图表大小
     */
    resizeAllCharts() {
        this.charts.forEach(chart => chart.resize());
    }
    
    /**
     * 导出图表为图片
     */
    exportChart(chartId, filename) {
        const chart = this.charts.get(chartId);
        if (!chart) return;
        
        const url = chart.toBase64Image('image/png', 1);
        const link = document.createElement('a');
        link.download = filename || `chart_${chartId}_${Date.now()}.png`;
        link.href = url;
        link.click();
    }
    
    /**
     * 获取图表实例
     */
    getChart(chartId) {
        return this.charts.get(chartId);
    }
    
    /**
     * 获取所有图表实例
     */
    getAllCharts() {
        return Array.from(this.charts.values());
    }
}

// 创建全局图表管理器实例
window.chartManager = new ChartManager();

// 窗口大小改变时调整图表
window.addEventListener('resize', () => {
    setTimeout(() => {
        window.chartManager.resizeAllCharts();
    }, 100);
});

// 页面卸载时销毁所有图表
window.addEventListener('beforeunload', () => {
    window.chartManager.destroyAllCharts();
});

// 导出图表函数
window.exportChart = (chartId, filename) => {
    window.chartManager.exportChart(chartId, filename);
};